<?php

namespace App\Admin\Controllers;

use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Show;
use App\Attachment;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class AttachmentController extends AdminController
{
    /**
     * Title for current resource.
     *
     * @var string
     */
    protected $title = '附件管理';

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new Attachment());
        $grid->model()->latest();
        $grid->column('id', __('附件id'));
        $grid->column('filename', __('预览'))->display(function ($filename) {
            return str_replace('uploads/', '', $filename);
        })->image();
        $grid->column('extension', '附件类型');
        $grid->column('size', __('附件尺寸'))->filesize();
        $grid->column('width', __('图片宽度'))->style('max-width:200px;word-break:break-all;');
        $grid->column('height', __('图片高度'))->style('max-width:200px;word-break:break-all;');
        $grid->disableCreateButton();
        $grid->disableFilter();
        $grid->disableExport();
        // $grid->disableRowSelector();
        return $grid;
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     * @return Show
     */
    protected function detail($id)
    {
        $show = new Show(Attachment::findOrFail($id));


        return $show;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $form = new Form(new Attachment());


        return $form;
    }

    public function upload(Request $request, Attachment $attachment)
    {
        $files = $request->files;
        $data = [];
        foreach ($files as $key => $file) {
            $path = date('Ym/d');
            $filename = '/uploads/' . Storage::disk('admin')->putFile($path, $request->file($key));
            $data[] = $filename;
            $size = Storage::disk('admin')->size(str_replace('uploads/', '', $filename));
            $extension = $request->file($key)->extension();
            if ($extension === 'jpeg' || $extension === 'jpg' || $extension === 'png' || $extension === 'gif' || $extension === 'webp' || $extension === 'bmp') {
                list($width, $height) = getimagesize(public_path() . $filename);
            } else {
                $width = 0;
                $height = 0;
            }
            $attachment->create(compact('filename', 'extension', 'size', 'width', 'height'));
        }
        return ['errno' => 0, 'data' => $data];
    }
}
